<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等 | Xiaoming&#39;s Blog | 一入前端深似海，从此妹子是路人。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="RegExp,正则表达式,正则验证">
    <meta name="description" content="什么是 RegExp？ RegExp 是正则表达式（Regular expression）的缩写，作用是对字符串执行模式匹配。  通常用于格式验证、正则替换、查找子串等  各种编程语言的正则表达式基本相同，不同的语言可能会有一些细小的差别">
<meta name="keywords" content="RegExp,正则表达式,正则验证">
<meta property="og:type" content="article">
<meta property="og:title" content="最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等">
<meta property="og:url" content="http://www.lovebxm.com/2017/05/31/RegExp/index.html">
<meta property="og:site_name" content="Xiaoming&#39;s Blog">
<meta property="og:description" content="什么是 RegExp？ RegExp 是正则表达式（Regular expression）的缩写，作用是对字符串执行模式匹配。  通常用于格式验证、正则替换、查找子串等  各种编程语言的正则表达式基本相同，不同的语言可能会有一些细小的差别">
<meta property="og:image" content="http://i2.muimg.com/567571/4f02d97b849fa998.png">
<meta property="og:updated_time" content="2017-05-31T03:36:01.918Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等">
<meta name="twitter:description" content="什么是 RegExp？ RegExp 是正则表达式（Regular expression）的缩写，作用是对字符串执行模式匹配。  通常用于格式验证、正则替换、查找子串等  各种编程语言的正则表达式基本相同，不同的语言可能会有一些细小的差别">
<meta name="twitter:image" content="http://i2.muimg.com/567571/4f02d97b849fa998.png">
    
        <link rel="alternate" type="application/atom+xml" title="Xiaoming&#39;s Blog" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu"  >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">白小明</h5>
          <a href="mailto:80583600@qq.com" title="80583600@qq.com" class="mail">80583600@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/hand-peace-o"  >
                <i class="icon icon-lg icon-hand-peace-o"></i>
                作品
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/bxm0927" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/user"  >
                <i class="icon icon-lg icon-user"></i>
                关于我
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404 测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-05-31T03:30:24.194Z" itemprop="datePublished" class="page-time">
  2017-05-31
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#什么是-RegExp？"><span class="post-toc-number">1.</span> <span class="post-toc-text">什么是 RegExp？</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#RegExp-语法"><span class="post-toc-number">2.</span> <span class="post-toc-text">RegExp 语法</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#概念：子表达式"><span class="post-toc-number">3.</span> <span class="post-toc-text">概念：子表达式</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#概念：方括号（字符簇）"><span class="post-toc-number">4.</span> <span class="post-toc-text">概念：方括号（字符簇）</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#概念：元字符"><span class="post-toc-number">5.</span> <span class="post-toc-text">概念：元字符</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#概念：量词"><span class="post-toc-number">6.</span> <span class="post-toc-text">概念：量词</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#RegExp-对象方法"><span class="post-toc-number">7.</span> <span class="post-toc-text">RegExp 对象方法</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#test"><span class="post-toc-number">7.1.</span> <span class="post-toc-text">test()</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#exec"><span class="post-toc-number">7.2.</span> <span class="post-toc-text">exec()</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#compile"><span class="post-toc-number">7.3.</span> <span class="post-toc-text">compile()</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#支持正则表达式的-String-对象的方法"><span class="post-toc-number">8.</span> <span class="post-toc-text">支持正则表达式的 String 对象的方法</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#search-检索与正则表达式相匹配的值。"><span class="post-toc-number">8.1.</span> <span class="post-toc-text">search   检索与正则表达式相匹配的值。</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#match-找到一个或多个正则表达式的匹配。"><span class="post-toc-number">8.2.</span> <span class="post-toc-text">match    找到一个或多个正则表达式的匹配。</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#replace-替换与正则表达式匹配的子串。"><span class="post-toc-number">8.3.</span> <span class="post-toc-text">replace  替换与正则表达式匹配的子串。</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#split-把字符串分割为字符串数组。"><span class="post-toc-number">8.4.</span> <span class="post-toc-text">split    把字符串分割为字符串数组。</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#经验："><span class="post-toc-number">8.4.1.</span> <span class="post-toc-text">经验：</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#常见的-正则表达式-校验"><span class="post-toc-number">9.</span> <span class="post-toc-text">常见的 正则表达式 校验</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#一、校验数字的表达式"><span class="post-toc-number">9.1.</span> <span class="post-toc-text">一、校验数字的表达式</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#二、校验字符的表达式"><span class="post-toc-number">9.2.</span> <span class="post-toc-text">二、校验字符的表达式</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#三、特殊需求表达式"><span class="post-toc-number">9.3.</span> <span class="post-toc-text">三、特殊需求表达式</span></a></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-RegExp"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等</h1>
        <div class="post-meta">
            <time class="post-time" title="2017-05-31 11:30:24" datetime="2017-05-31T03:30:24.194Z"  itemprop="datePublished">2017-05-31</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="什么是-RegExp？"><a href="#什么是-RegExp？" class="headerlink" title="什么是 RegExp？"></a>什么是 RegExp？</h1><ul>
<li><p>RegExp 是正则表达式（Regular expression）的缩写，作用是对字符串执行模式匹配。</p>
</li>
<li><p>通常用于格式验证、正则替换、查找子串等</p>
</li>
<li><p>各种编程语言的正则表达式基本相同，不同的语言可能会有一些细小的差别</p>
</li>
</ul>
<a id="more"></a>
<ul>
<li><p>RegExp入门：<a href="http://www.w3school.com.cn/js/js_obj_regexp.asp" target="_blank" rel="external">http://www.w3school.com.cn/js/js_obj_regexp.asp</a></p>
</li>
<li><p>完整的 RegExp 对象参考手册：<a href="http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp" target="_blank" rel="external">http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp</a></p>
</li>
<li><p>PHP 正则表达式：<a href="http://www.imooc.com/learn/350" target="_blank" rel="external">http://www.imooc.com/learn/350</a></p>
</li>
<li><p>javascript 正则表达式：<a href="http://www.imooc.com/learn/706" target="_blank" rel="external">http://www.imooc.com/learn/706</a></p>
</li>
<li><p>Python 正则表达式：<a href="http://www.imooc.com/learn/550" target="_blank" rel="external">http://www.imooc.com/learn/550</a></p>
</li>
</ul>
<!-- more -->
<h1 id="RegExp-语法"><a href="#RegExp-语法" class="headerlink" title="RegExp 语法"></a>RegExp 语法</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 直接实例化</span></div><div class="line"><span class="keyword">var</span> reg = <span class="keyword">new</span> <span class="built_in">RegExp</span>(pattern [, flags]);</div><div class="line"></div><div class="line"><span class="comment">// 隐式创建(推荐)</span></div><div class="line"><span class="keyword">var</span> reg = <span class="regexp">/pattern/</span>flags;</div></pre></td></tr></table></figure>
<p>参数 pattern 是一个字符串，指定了正则表达式的模式或其他正则表达式。</p>
<p>参数 [, flags] 是一个可选的字符串，包含属性 “g”（global ）、”i” （ignoreCase）和 “m”（multiline）。</p>
<p>ECMAScript 标准化之前，不支持 m 属性。如果 pattern 是正则表达式，而不是字符串，则必须省略该参数。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="http://i2.muimg.com/567571/4f02d97b849fa998.png" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure>
<h1 id="概念：子表达式"><a href="#概念：子表达式" class="headerlink" title="概念：子表达式"></a>概念：子表达式</h1><p>在正则表达式中，使用括号括起来的内容是一个<strong>子表达式</strong>，子表达式匹配到的内容会被系统<strong>捕获</strong>至缓冲区，使用\n（n：数字）来<strong>反向引用</strong>系统的第n号缓冲区的内容。</p>
<p>场景：后面的内容要求与前面的一致，可以使用子表达式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 查找连续相同的四个数字</span></div><div class="line"><span class="keyword">var</span> str = <span class="string">"1212ab45677778cd"</span>;</div><div class="line"><span class="keyword">var</span> reg = <span class="regexp">/(\d)\1\1\1/gi</span>;</div><div class="line"><span class="built_in">console</span>.log(str.match(reg));</div><div class="line"><span class="comment">// OUTPUT:7777</span></div></pre></td></tr></table></figure>
<h1 id="概念：方括号（字符簇）"><a href="#概念：方括号（字符簇）" class="headerlink" title="概念：方括号（字符簇）"></a>概念：方括号（字符簇）</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> str = <span class="string">"Is this all there is?"</span>;</div><div class="line"><span class="keyword">var</span> patt1 = <span class="regexp">/[a-h]/g</span>;</div><div class="line"><span class="built_in">document</span>.write(str.match(patt1));</div><div class="line"><span class="comment">// OUTPUT:h,a,h,e,e</span></div></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th>方括号</th>
<th>作用</th>
</tr>
</thead>
<tbody>
<tr>
<td>[abc]</td>
<td>查找方括号之间的任何字符。</td>
</tr>
<tr>
<td>[^abc]</td>
<td>查找任何不在方括号之间的字符。</td>
</tr>
<tr>
<td>[0-9]</td>
<td>查找任何从 0 至 9 的数字。同 \d</td>
</tr>
<tr>
<td>[a-z]</td>
<td>查找任何从小写 a 到小写 z 的字符。</td>
</tr>
<tr>
<td>[A-Z]</td>
<td>查找任何从大写 A 到大写 Z 的字符。</td>
</tr>
<tr>
<td>[A-z]</td>
<td>查找任何从大写 A 到小写 z 的字符。</td>
</tr>
<tr>
<td>[0-9a-zA-Z]</td>
<td>查找0-9,a-z,A-Z</td>
</tr>
</tbody>
</table>
<h1 id="概念：元字符"><a href="#概念：元字符" class="headerlink" title="概念：元字符"></a>概念：元字符</h1><p>元字符（Metacharacter）是拥有特殊含义的字符：<br>元字符 | 作用<br>—|—<br>\ | 转义符 （、）、/、\<br>| | 选择匹配符，可以匹配多个规则<br>. | 查找单个字符，除了换行和行结束符。<br>\w | 查找单词字符。字符 ( 字母 ，数字，下划线_ )<br>\W | 查找非单词字符。<br>\d | 查找数字。<br>\D | 查找非数字字符。<br>\s | 查找空白字符。空格<br>\S | 查找非空白字符。<br>\b | 匹配单词边界。<br>\B | 匹配非单词边界。<br>\0 | 查找 NUL 字符。<br>\n | 查找换行符。<br>\f | 查找换页符。<br>\r | 查找回车符。<br>\t | 查找制表符。<br>\v | 查找垂直制表符。<br>\xxx | 查找以八进制数 xxx 规定的字符。<br>\xdd | 查找以十六进制数 dd 规定的字符。<br>\uxxxx | 查找以十六进制数 xxxx 规定的 Unicode 字符。</p>
<h1 id="概念：量词"><a href="#概念：量词" class="headerlink" title="概念：量词"></a>概念：量词</h1><table>
<thead>
<tr>
<th>量词</th>
<th>作用</th>
</tr>
</thead>
<tbody>
<tr>
<td>n+</td>
<td>匹配任何包含至少一个 n 的字符串。同 {1,}</td>
</tr>
<tr>
<td>n*</td>
<td>匹配任何包含零个或多个 n 的字符串。同 {0,}</td>
</tr>
<tr>
<td>n?</td>
<td>匹配任何包含零个或一个 n 的字符串。同 {0,1}</td>
</tr>
<tr>
<td>n{X}</td>
<td>匹配包含 X 个 n 的序列的字符串。</td>
</tr>
<tr>
<td>n{X,Y}</td>
<td>匹配包含 X 至 Y 个 n 的序列的字符串。</td>
</tr>
<tr>
<td>n{X,}</td>
<td>匹配包含至少 X 个 n 的序列的字符串。</td>
</tr>
<tr>
<td>n$</td>
<td>匹配任何<strong>结尾</strong>为 n 的字符串。</td>
</tr>
<tr>
<td>^n</td>
<td>匹配任何<strong>开头</strong>为 n 的字符串。注意 /[^a] / 和 /^ [a]/是不一样的，前者是排除的，后者是代表首位。</td>
</tr>
<tr>
<td>(?=n)</td>
<td>匹配任何其后紧接指定字符串 n 的字符串。<strong>正向预查</strong></td>
</tr>
<tr>
<td>(?!n)</td>
<td>匹配任何其后没有紧接指定字符串 n 的字符串。<strong>反向预查</strong></td>
</tr>
</tbody>
</table>
<h1 id="RegExp-对象方法"><a href="#RegExp-对象方法" class="headerlink" title="RegExp 对象方法"></a>RegExp 对象方法</h1><h2 id="test"><a href="#test" class="headerlink" title="test()"></a>test()</h2><p>test() 方法检索字符串中是否存在指定的值。返回值是 true 或 false。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> patt1 = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'e'</span>);</div><div class="line"><span class="built_in">console</span>.log(patt1.test(<span class="string">'some text'</span>));</div><div class="line"><span class="comment">// OUTPUT:true</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> patt2 = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'ee'</span>);</div><div class="line"><span class="built_in">console</span>.log(patt2.test(<span class="string">'some text'</span>));</div><div class="line"><span class="comment">// OUTPUT:false</span></div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 判断是不是QQ号</span></div><div class="line"><span class="comment">// 1 首位不能是0  ^[1-9]</span></div><div class="line"><span class="comment">// 2 必须是 [5, 11] 位的数字 \d&#123;4, 9&#125;</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> str = <span class="string">'80583600'</span>;</div><div class="line"><span class="keyword">var</span> regexp = <span class="regexp">/^[1-9][0-9]&#123;4,10&#125;$/gim</span>;</div><div class="line"><span class="keyword">if</span> (regexp.test(str)) &#123;</div><div class="line">    alert(<span class="string">'is'</span>);</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    alert(<span class="string">'no'</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="exec"><a href="#exec" class="headerlink" title="exec()"></a>exec()</h2><p>exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配，则返回 null。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> patt1 = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'e'</span>);</div><div class="line"><span class="built_in">console</span>.log(patt1.exec(<span class="string">'some text'</span>));</div><div class="line"><span class="comment">// OUTPUT:e</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> patt2 = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'ee'</span>);</div><div class="line"><span class="built_in">console</span>.log(patt2.exec(<span class="string">'some text'</span>));</div><div class="line"><span class="comment">// OUTPUT:null</span></div></pre></td></tr></table></figure>
<h2 id="compile"><a href="#compile" class="headerlink" title="compile()"></a>compile()</h2><p>compile() 既可以改变检索模式，也可以添加或删除第二个参数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> patt1=<span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">"e"</span>);</div><div class="line"><span class="built_in">document</span>.write(patt1.test(<span class="string">"The best things in life are free"</span>)); <span class="comment">// true</span></div><div class="line"></div><div class="line"><span class="comment">// 改变了检索模式</span></div><div class="line">patt1.compile(<span class="string">"eee"</span>);</div><div class="line"><span class="built_in">document</span>.write(patt1.test(<span class="string">"The best things in life are free"</span>)); <span class="comment">// false</span></div></pre></td></tr></table></figure>
<h1 id="支持正则表达式的-String-对象的方法"><a href="#支持正则表达式的-String-对象的方法" class="headerlink" title="支持正则表达式的 String 对象的方法"></a>支持正则表达式的 String 对象的方法</h1><h2 id="search-检索与正则表达式相匹配的值。"><a href="#search-检索与正则表达式相匹配的值。" class="headerlink" title="search   检索与正则表达式相匹配的值。"></a>search   检索与正则表达式相匹配的值。</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> str = <span class="string">"Visit W3School!"</span></div><div class="line"><span class="built_in">console</span>.log(str.search(<span class="regexp">/W3School/</span>))</div><div class="line"><span class="comment">// OUTPUT:6</span></div></pre></td></tr></table></figure>
<h2 id="match-找到一个或多个正则表达式的匹配。"><a href="#match-找到一个或多个正则表达式的匹配。" class="headerlink" title="match    找到一个或多个正则表达式的匹配。"></a>match    找到一个或多个正则表达式的匹配。</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> str=<span class="string">"1 plus 2 equal 3"</span></div><div class="line"><span class="built_in">console</span>.log(str.match(<span class="regexp">/\d+/g</span>))</div><div class="line"><span class="comment">// OUTPUT:1,2,3</span></div></pre></td></tr></table></figure>
<h2 id="replace-替换与正则表达式匹配的子串。"><a href="#replace-替换与正则表达式匹配的子串。" class="headerlink" title="replace  替换与正则表达式匹配的子串。"></a>replace  替换与正则表达式匹配的子串。</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> str = <span class="string">"Visit Microsoft!"</span></div><div class="line"><span class="built_in">console</span>.log(str.replace(<span class="regexp">/Microsoft/</span>, <span class="string">"W3School"</span>));</div><div class="line"><span class="comment">// OUTPUT:Visit W3School!</span></div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 找重复项最多的字符个数</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> str = <span class="string">'g21ss4aeba_ersb43sgnnsssstht6sss60snnsj8resw0_ss'</span>;</div><div class="line"></div><div class="line"><span class="comment">// split : 将字符串转化为数组</span></div><div class="line"><span class="comment">// sort : 对数组排序，ASCII</span></div><div class="line"><span class="comment">// join : 将数组转化为字符串</span></div><div class="line"><span class="keyword">var</span> str_new = str.split(<span class="string">''</span>).sort().join(<span class="string">''</span>);</div><div class="line"><span class="built_in">document</span>.write(str + <span class="string">'&lt;br&gt;'</span>);</div><div class="line"><span class="built_in">document</span>.write(str.split(<span class="string">''</span>) + <span class="string">'&lt;br&gt;'</span>);</div><div class="line"><span class="built_in">document</span>.write(str.split(<span class="string">''</span>).sort() + <span class="string">'&lt;br&gt;'</span>);</div><div class="line"><span class="built_in">document</span>.write(str.split(<span class="string">''</span>).sort().join(<span class="string">''</span>) + <span class="string">'&lt;br&gt;'</span>);</div><div class="line"></div><div class="line"><span class="comment">// 匹配字符，且重复这个字符，重复次数至少一次。</span></div><div class="line"><span class="keyword">var</span> regexp = <span class="regexp">/(\w)\1+/g</span>;</div><div class="line"></div><div class="line"><span class="keyword">var</span> index = <span class="number">0</span>;</div><div class="line"><span class="keyword">var</span> value = <span class="string">''</span>;</div><div class="line"></div><div class="line">str_new.replace(regexp, <span class="function"><span class="keyword">function</span>(<span class="params">$<span class="number">0</span>, $<span class="number">1</span></span>) </span>&#123;</div><div class="line">    <span class="comment">// document.write($0);</span></div><div class="line">    <span class="comment">// document.write($1);</span></div><div class="line">    <span class="keyword">if</span> (index &lt; $<span class="number">0.</span>length) &#123;</div><div class="line">        index = $<span class="number">0.</span>length;</div><div class="line">        value = $<span class="number">1</span>;</div><div class="line">    &#125;</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="built_in">document</span>.write(<span class="string">'重复项最多的字符是：'</span> + value + <span class="string">'，个数是：'</span> + index);</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">// OUTPUT:</span></div><div class="line"><span class="comment">// 0012344668__aabbeeegghjnnnnrrssssssssssssssssttw</span></div><div class="line"><span class="comment">// 重复项最多的字符是：s，个数是：16</span></div></pre></td></tr></table></figure>
<h2 id="split-把字符串分割为字符串数组。"><a href="#split-把字符串分割为字符串数组。" class="headerlink" title="split    把字符串分割为字符串数组。"></a>split    把字符串分割为字符串数组。</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> str = <span class="string">"How are you doing today?"</span></div><div class="line"><span class="built_in">document</span>.write(str.split(<span class="regexp">/\s+/</span>));</div><div class="line"><span class="comment">// OUTPUT:How,are,you,doing,today?</span></div></pre></td></tr></table></figure>
<blockquote>
<h3 id="经验："><a href="#经验：" class="headerlink" title="经验："></a>经验：</h3><ol>
<li>检验格式（邮箱格式、IP格式）是否正确，用test()</li>
<li>抓取星期（如所有手机号），用exec()、match()</li>
<li>替换敏感词汇，用replace()</li>
</ol>
</blockquote>
<h1 id="常见的-正则表达式-校验"><a href="#常见的-正则表达式-校验" class="headerlink" title="常见的 正则表达式 校验"></a>常见的 正则表达式 校验</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div><div class="line">155</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 常见的 正则表达式 校验</span></div><div class="line"><span class="comment">// QQ号、手机号、Email、是否是数字、去掉前后空格、是否存在中文、邮编、身份证、URL、日期格式、IP</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> myRegExp = &#123;</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法QQ号码</span></div><div class="line">    isQQ: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="comment">// 1 首位不能是0  ^[1-9]</span></div><div class="line">        <span class="comment">// 2 必须是 [5, 11] 位的数字  \d&#123;4, 9&#125;</span></div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^[1-9][0-9]&#123;4,9&#125;$/gim</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'QQ号码格式输入正确'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'请输入正确格式的QQ号码'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法手机号码</span></div><div class="line">    isPhone: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57]|17[678])[0-9]&#123;8&#125;$/</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'手机号码格式输入正确'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'请输入正确格式的手机号码'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法Email地址</span></div><div class="line">    isEmail: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/</span>;</div><div class="line">        <span class="comment">// var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;</span></div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'Email格式输入正确'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'请输入正确格式的Email'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否是数字</span></div><div class="line">    isNumber: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^\d+$/</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">'是数字'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">'不是数字'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 去掉前后空格</span></div><div class="line">    trim: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^\s+|\s+$/g</span>;</div><div class="line">        <span class="keyword">return</span> str.replace(reg, <span class="string">''</span>);</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否存在中文</span></div><div class="line">    isChinese: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/[\u4e00-\u9fa5]/gm</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 中存在中文'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 中不存在中文'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法邮政编码</span></div><div class="line">    isPostcode: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="comment">// 起始数字不能为0，然后是5个数字  [1-9]\d&#123;5&#125;</span></div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^[1-9]\d&#123;5&#125;$/g</span>;</div><div class="line">        <span class="comment">// var reg = /^[1-9]\d&#123;5&#125;(?!\d)$/;</span></div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是合法的邮编格式'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是不合法的邮编格式'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法身份证号码</span></div><div class="line">    isIDcard: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^(^[1-9]\d&#123;7&#125;((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d&#123;3&#125;$)|(^[1-9]\d&#123;5&#125;[1-9]\d&#123;3&#125;((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d&#123;4&#125;)|\d&#123;3&#125;[Xx])$)$/</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是合法的身份证号码'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是不合法的身份证号码'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法URL</span></div><div class="line">    isURL: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&amp;?[a-zA-Z0-9_-](\?)?)*)*$/i</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是合法的URL'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是不合法的URL'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法日期格式 yyyy-mm-dd</span></div><div class="line">    isDate: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^[1-2][0-9][0-9][0-9]-[0-1]&#123;0,1&#125;[0-9]-[0-3]&#123;0,1&#125;[0-9]$/</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是合法的日期格式'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是不合法的日期格式，yyyy-mm-dd'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"></div><div class="line">    <span class="comment">// 检查字符串是否为合法IP地址</span></div><div class="line">    isIP: <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>&#123;</div><div class="line">        <span class="comment">// 1.1.1.1  四段  [0 , 255]</span></div><div class="line">        <span class="comment">// 第一段不能为0</span></div><div class="line">        <span class="comment">// 每个段不能以0开头</span></div><div class="line">        <span class="comment">//</span></div><div class="line">        <span class="comment">// 本机IP: 58.50.120.18 湖北省荆州市 电信</span></div><div class="line">        <span class="keyword">var</span> reg = <span class="regexp">/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]))&#123;3&#125;$/gi</span>;</div><div class="line">        <span class="keyword">if</span> (reg.test(str)) &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是合法的IP地址'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="built_in">console</span>.log(str + <span class="string">' 是不合法的IP地址'</span>);</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 测试</span></div><div class="line"><span class="comment">// console.log(myRegExp.isQQ('80583600'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isPhone('17607160722'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isEmail('80583600@qq.com'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isNumber('100a'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.trim('  100  '));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isChinese('baixiaoming'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isChinese('小明'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isPostcode('412345'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isIDcard('42091119940927001X'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isURL('https://www.baidu.com/'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isDate('2017-4-4'));</span></div><div class="line"><span class="comment">// console.log(myRegExp.isIP('1.0.0.0'));</span></div></pre></td></tr></table></figure>
<h2 id="一、校验数字的表达式"><a href="#一、校验数字的表达式" class="headerlink" title="一、校验数字的表达式"></a>一、校验数字的表达式</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">数字：^[0-9]*$</div><div class="line">n位的数字：^\d&#123;n&#125;$</div><div class="line">至少n位的数字：^\d&#123;n,&#125;$</div><div class="line">m-n位的数字：^\d&#123;m,n&#125;$</div><div class="line">零和非零开头的数字：^(0|[1-9][0-9]*)$</div><div class="line">非零开头的最多带两位小数的数字：^([1-9][0-9]*)+(.[0-9]&#123;1,2&#125;)?$</div><div class="line">带1-2位小数的正数或负数：^(\-)?\d+(\.\d&#123;1,2&#125;)?$</div><div class="line">正数、负数、和小数：^(\-|\+)?\d+(\.\d+)?$</div><div class="line">有两位小数的正实数：^[0-9]+(.[0-9]&#123;2&#125;)?$</div><div class="line">有1~3位小数的正实数：^[0-9]+(.[0-9]&#123;1,3&#125;)?$</div><div class="line">非零的正整数：^[1-9]\d*$ 或 ^([1-9][0-9]*)&#123;1,3&#125;$ 或 ^\+?[1-9][0-9]*$</div><div class="line">非零的负整数：^\-[1-9][]0-9&quot;*$ 或 ^-[1-9]\d*$</div><div class="line">非负整数：^\d+$ 或 ^[1-9]\d*|0$</div><div class="line">非正整数：^-[1-9]\d*|0$ 或 ^((-\d+)|(0+))$</div><div class="line">非负浮点数：^\d+(\.\d+)?$ 或 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$</div><div class="line">非正浮点数：^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 或 ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$</div><div class="line">正浮点数：^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 或 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$</div><div class="line">负浮点数：^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ 或 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$</div><div class="line">浮点数：^(-?\d+)(\.\d+)?$ 或 ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$</div></pre></td></tr></table></figure>
<h2 id="二、校验字符的表达式"><a href="#二、校验字符的表达式" class="headerlink" title="二、校验字符的表达式"></a>二、校验字符的表达式</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">汉字：^[\u4e00-\u9fa5]&#123;0,&#125;$</div><div class="line">英文和数字：^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]&#123;4,40&#125;$</div><div class="line">长度为3-20的所有字符：^.&#123;3,20&#125;$</div><div class="line">由26个英文字母组成的字符串：^[A-Za-z]+$</div><div class="line">由26个大写英文字母组成的字符串：^[A-Z]+$</div><div class="line">由26个小写英文字母组成的字符串：^[a-z]+$</div><div class="line">由数字和26个英文字母组成的字符串：^[A-Za-z0-9]+$</div><div class="line">由数字、26个英文字母或者下划线组成的字符串：^\w+$ 或 ^\w&#123;3,20&#125;$</div><div class="line">中文、英文、数字包括下划线：^[\u4E00-\u9FA5A-Za-z0-9_]+$</div><div class="line">可以输入含有^%&amp;&apos;,;=?$\&quot;等字符：[^%&amp;&apos;,;=?$\x22]+</div><div class="line">禁止输入含有~的字符：[^~\x22]+</div></pre></td></tr></table></figure>
<h2 id="三、特殊需求表达式"><a href="#三、特殊需求表达式" class="headerlink" title="三、特殊需求表达式"></a>三、特殊需求表达式</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line">Email地址：^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$</div><div class="line">域名：[a-zA-Z0-9][-a-zA-Z0-9]&#123;0,62&#125;(/.[a-zA-Z0-9][-a-zA-Z0-9]&#123;0,62&#125;)+/.?</div><div class="line">InternetURL：[a-zA-z]+://[^\s]* 或 ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&amp;=]*)?$</div><div class="line">手机号码：^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d&#123;8&#125;$</div><div class="line">电话号码(&quot;XXX-XXXXXXX&quot;、&quot;XXXX-XXXXXXXX&quot;、&quot;XXX-XXXXXXX&quot;、&quot;XXX-XXXXXXXX&quot;、&quot;XXXXXXX&quot;和&quot;XXXXXXXX)：^(\(\d&#123;3,4&#125;-)|\d&#123;3.4&#125;-)?\d&#123;7,8&#125;$</div><div class="line">国内电话号码(0511-4405222、021-87888822)：\d&#123;3&#125;-\d&#123;8&#125;|\d&#123;4&#125;-\d&#123;7&#125;</div><div class="line">身份证号(15位、18位数字)：^\d&#123;15&#125;|\d&#123;18&#125;$</div><div class="line">短身份证号码(数字、字母x结尾)：^([0-9])&#123;7,18&#125;(x|X)?$ 或 ^\d&#123;8,18&#125;|[0-9x]&#123;8,18&#125;|[0-9X]&#123;8,18&#125;?$</div><div class="line">帐号是否合法(字母开头，允许5-16字节，允许字母数字下划线)：^[a-zA-Z][a-zA-Z0-9_]&#123;4,15&#125;$</div><div class="line">密码(以字母开头，长度在6~18之间，只能包含字母、数字和下划线)：^[a-zA-Z]\w&#123;5,17&#125;$</div><div class="line">强密码(必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间)：^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).&#123;8,10&#125;$</div><div class="line">日期格式：^\d&#123;4&#125;-\d&#123;1,2&#125;-\d&#123;1,2&#125;</div><div class="line">一年的12个月(01～09和1～12)：^(0?[1-9]|1[0-2])$</div><div class="line">一个月的31天(01～09和1～31)：^((0?[1-9])|((1|2)[0-9])|30|31)$</div><div class="line">xml文件：^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$</div><div class="line">中文字符的正则表达式：[\u4e00-\u9fa5]</div><div class="line">双字节字符：[^\x00-\xff]    (包括汉字在内，可以用来计算字符串的长度(一个双字节字符长度计2，ASCII字符计1))</div><div class="line">空白行的正则表达式：\n\s*\r    (可以用来删除空白行)</div><div class="line">HTML标记的正则表达式：&lt;(\S*?)[^&gt;]*&gt;.*?&lt;/\1&gt;|&lt;.*? /&gt;    (网上流传的版本太糟糕，上面这个也仅仅能部分，对于复杂的嵌套标记依旧无能为力)</div><div class="line">首尾空白字符的正则表达式：^\s*|\s*$或(^\s*)|(\s*$)    (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等)，非常有用的表达式)</div><div class="line">腾讯QQ号：[1-9][0-9]&#123;4,&#125;    (腾讯QQ号从10000开始)</div><div class="line">中国邮政编码：[1-9]\d&#123;5&#125;(?!\d)    (中国邮政编码为6位数字)</div><div class="line">IP地址：\d+\.\d+\.\d+\.\d+    (提取IP地址时有用)</div><div class="line">IP地址：((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.)&#123;3&#125;(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))</div></pre></td></tr></table></figure>
<p>钱的输入格式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">1.有四种钱的表示形式我们可以接受:&quot;10000.00&quot; 和 &quot;10,000.00&quot;, 和没有 &quot;分&quot; 的 &quot;10000&quot; 和 &quot;10,000&quot;：^[1-9][0-9]*$</div><div class="line">2.这表示任意一个不以0开头的数字,但是,这也意味着一个字符&quot;0&quot;不通过,所以我们采用下面的形式：^(0|[1-9][0-9]*)$</div><div class="line">3.一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号：^(0|-?[1-9][0-9]*)$</div><div class="line">4.这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分：^[0-9]+(.[0-9]+)?$</div><div class="line">5.必须说明的是,小数点后面至少应该有1位数,所以&quot;10.&quot;是不通过的,但是 &quot;10&quot; 和 &quot;10.2&quot; 是通过的：^[0-9]+(.[0-9]&#123;2&#125;)?$</div><div class="line">6.这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样：^[0-9]+(.[0-9]&#123;1,2&#125;)?$</div><div class="line">7.这样就允许用户只写一位小数.下面我们该考虑数字中的逗号了,我们可以这样：^[0-9]&#123;1,3&#125;(,[0-9]&#123;3&#125;)*(.[0-9]&#123;1,2&#125;)?$</div><div class="line">8.1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须：^([0-9]+|[0-9]&#123;1,3&#125;(,[0-9]&#123;3&#125;)*)(.[0-9]&#123;1,2&#125;)?$</div><div class="line">备注：这就是最终结果了,别忘了&quot;+&quot;可以用&quot;*&quot;替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里</div></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-05-31T03:36:01.918Z" itemprop="dateUpdated">2017-05-31 11:36:01</time>
</span><br>


        
        原始文章链接：<a href="/2017/05/31/RegExp/" target="_blank" rel="external">http://www.lovebxm.com/2017/05/31/RegExp/</a>
        
    </div>
    <footer>
        <a href="http://www.lovebxm.com">
            <img src="/img/avatar.jpg" alt="白小明">
            白小明
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/RegExp/">RegExp</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/正则表达式/">正则表达式</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/正则验证/">正则验证</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://www.lovebxm.com/2017/05/31/RegExp/&title=《最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等》 — Xiaoming's Blog&pic=http://www.lovebxm.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://www.lovebxm.com/2017/05/31/RegExp/&title=《最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等》 — Xiaoming's Blog&source=什么是 RegExp？
RegExp 是正则表达式（Regular expression）的缩写，作用是对字符串执行模式匹配。

通常用于格式验证、正则替..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://www.lovebxm.com/2017/05/31/RegExp/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等》 — Xiaoming's Blog&url=http://www.lovebxm.com/2017/05/31/RegExp/&via=http://www.lovebxm.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://www.lovebxm.com/2017/05/31/RegExp/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/06/24/es6_study/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">学习 ES6，一篇文章就够了</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/05/30/PHP_Cookie_Session/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">PHP cookie 与 session</h4>
      </a>
    </div>
  
</nav>



    










    <div id="cloud-tie-wrapper" class="comments cloud-tie-wrapper"></div>
    <script>
    var cloudTieConfig = {
        url: 'http://www.lovebxm.com/2017/05/31/RegExp/index.html',
        sourceId: 'RegExp',
        productKey: '294c776acae94037bdd6605780e549e4',
        target: 'cloud-tie-wrapper',
        pcFiles: [
            '//unpkg.com/hexo-theme-material-indigo@latest/css/cloudTie/pc.css',
            '//unpkg.com/hexo-theme-material-indigo@latest/js/cloudTie/pc.min.js',
        ],
        mobileFiles: [
            '//unpkg.com/hexo-theme-material-indigo@latest/css/cloudTie/mobile.css',
            '//unpkg.com/hexo-theme-material-indigo@latest/js/cloudTie/mobile.min.js'
        ]
    };
    </script>
    <script src="//unpkg.com/hexo-theme-material-indigo@latest/js/cloudTie/loader.min.js"></script>







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢您~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.jpg" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <!-- <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循<a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a></span>
            <span>白小明 &copy; 2017</span>
        </p>
    </div>
</footer> -->

<footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循<a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
            <span>白小明 &copy; 2017</span>
        </p>
    </div>
    <div class="bottom">
        <p>
        <span>
        <a target="_blank" href="mailto:80583600@qq.com" style="border-bottom:none">
        <img src="" alt="E-mail 联系" style="width:20px;height:20px;border:none;">
        </a>
        </span>

        <span>
        <a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=80583600&site=qq&menu=yes" style="border-bottom:none">
        <img src="" title="QQ 联系" style="width:22px;height:22px;border:none;"></a>
        </span>

        <span>
        <a target="_blank" href="https://github.com/bxm0927" style="border-bottom:none">
        <img src="" alt="GitHub microzz" title="GitHub 联系" style="width:19px;height:19px;border:none;"></a>
        </span>
        </p>
    </div>
</footer>




    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://www.lovebxm.com/2017/05/31/RegExp/&title=《最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等》 — Xiaoming's Blog&pic=http://www.lovebxm.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://www.lovebxm.com/2017/05/31/RegExp/&title=《最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等》 — Xiaoming's Blog&source=什么是 RegExp？
RegExp 是正则表达式（Regular expression）的缩写，作用是对字符串执行模式匹配。

通常用于格式验证、正则替..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://www.lovebxm.com/2017/05/31/RegExp/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等》 — Xiaoming's Blog&url=http://www.lovebxm.com/2017/05/31/RegExp/&via=http://www.lovebxm.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://www.lovebxm.com/2017/05/31/RegExp/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
